<template>
  <div>
    <div class="gva-table-box">
      <div style="margin-bottom: 20px;">
        <el-input
          v-model="searchInfo.keyword"
          placeholder="请输入项目名称"
          style="width: 15%;margin-right: 20px;"
        />
        <el-cascader
          v-model="searchInfo.status"
          clearable
          style="width: 15%;margin-right: 20px;"
          :options="options"
        />
        <el-select
          v-model="hugeSelectColumn"
          multiple
          clearable
          filterable
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          placeholder="请选择列"
          style="width: 500px;margin-right: 20px;"
          @change="selectHugeColumn"
        >
          <el-option
            v-for="item in hugeColumns"
            :key="item.prop"
            :label="item.label"
            :value="item.prop"
          />
        </el-select>
        <el-button
          type="primary"
          @click="search()"
        >
          查询
        </el-button>
        <el-button
          type="primary"
          style="float: right;"
          @click="create()"
        >创建</el-button>
      </div>
      <el-divider />
      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        row-key="ID"
        :data="hugeTableData"
        border
      >
        <el-table-column
          align="left"
          label="项目名称"
          width="330px"
          prop="name"
          fixed="left"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="advertList(scope.row)"
            >
              {{ scope.row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200px"
          fixed="left"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.operationStatus"
              style="padding-right: 20px;"
              @change="updateStatusProjectSwitch(scope.row)"
            />
            <el-button
              link
              type="primary"
              @click="editProject(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              @click="deleteProject(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="项目ID"
          width="200px"
          prop="project_id"
          fixed="left"
        />
        <el-table-column
          v-for="(item,index) in temHugeSelectColumn"
          :key="index"
          :width="item.width"
          align="left"
          :label="item.label"
        >
          <template #default="scope">
            <span style="margin-right: 5px;">
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-drawer
        v-model="createDialog"
        size="60%"
        title="创建项目"
        width="800"
      >
        <el-form
          ref="project"
          :model="projectForm"
          label-position="top"
          :validate-on-rule-change="false"
        >
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>项目名称</span>
              </div>
            </template>
            <el-form-item
              label="项目名称"
              label-width="140px"
              prop="name"
            >
              <el-input
                v-model="projectForm.name"
                style="width: 50%;"
              />
            </el-form-item>
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>营销目的与场景</span>
              </div>
            </template>
            <marketing-info
              :cur-value="marketCurValue"
              @receive="marketReceive"
            />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>投放内容与目标</span>
              </div>
            </template>
            <el-form-item
              label="投放内容"
              label-width="140px"
              prop="micro_promotion_type"
            >
              <el-radio-group
                v-model="projectForm.micro_promotion_type"
              >
                <el-radio-button
                  v-for="(item,index) in micro_promotion_type_list"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="字节小游戏"
              label-width="140px"
              prop="micro_app_instance_id"
            >
              <el-select
                v-model="projectForm.micro_app_instance_id"
                style="width: 40%;"
                @change="changeMicroAppInstance"
              >
                <el-option
                  v-for="(item,index) in micro_app_instance_id_list"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="事件资产"
              label-width="140px"
              prop="asset_ids"
            >
              <el-select
                v-model.number="projectForm.optimize_goal.asset_ids[0]"
                style="width: 40%;"
              >
                <el-option
                  v-for="(item,index) in asset_ids_list"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="优化目标"
              label-width="140px"
              prop="external_action"
            >
              <el-select
                v-model="projectForm.optimize_goal.external_action"
                style="width: 30%;"
              >
                <el-option
                  v-for="(item,index) in external_action_list"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-card>
          <div v-if="marketCurValue.delivery_mode == 'MANUAL'">
            <el-divider />
            <el-card>
              <template #header>
                <div
                  class="card-header"
                >
                  <span>投放板位</span>
                </div>
              </template>
              <el-form-item
                label="投放位置"
                label-width="140px"
                prop="inventory_catalog"
              >
                <el-radio-group
                  v-model="projectForm.delivery_range.inventory_catalog"
                  style="width: 50%;"
                >
                  <el-radio-button
                    v-for="item in inventory_catalog_list"
                    :key="item.value"
                    :label="item.value"
                    :disabled="item.disabled"
                  >
                    {{ item.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-select
                v-if="projectForm.delivery_range.inventory_catalog == 'MANUAL'"
                v-model="projectForm.delivery_range.inventory_type"
                style="width: 40%;"
                multiple
                @chnage="changeInventoryType"
              >
                <el-option
                  v-for="(item,index) in inventory_type_list"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-card>
          </div>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>用户定向</span>
              </div>
            </template>
            <audience-target
              :cur-value="curValue"
              :extensions="extensions"
              @receive="receive"
            />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>排期与预算</span>
              </div>
            </template>
            <budget-schedule
              :cur-value="budgetCurValue"
              :extensions="budgetExtensions"
              @receive="budgetReceive"
            />
          </el-card>
          <el-divider />
          <el-card v-if="searchControl">
            <template #header>
              <div
                class="card-header"
              >
                <span>搜索快投</span>
              </div>
            </template>
            <el-form-item
              label="关键词"
              label-width="140px"
            >
              <el-select
                v-model="keywordModel"
                multiple
                collapse-tags
                clearable
                filterable
                multiple-limit="1000"
                style="width: 25%;padding-right:10px"
              >
                <el-option
                  v-for="(item,index) in keywordList"
                  :key="index"
                  :label="item.word"
                  :value="item.word"
                />
              </el-select>
              <el-button
                type="primary"
                @click="openKeywordDialog"
              >添加/编辑</el-button>
            </el-form-item>
            <el-form-item
              label="出价系数"
              label-width="140px"
            >
              <el-input-number
                v-model="projectForm.search_bid_ratio"
                style="width: 20%;"
                :precision="2"
              />
            </el-form-item>
            <el-form-item
              label="定向扩展"
              label-width="140px"
            >
              <el-radio-group
                v-model="projectForm.audience_extend"
                style="width: 50%;"
              >
                <el-radio-button
                  v-for="item in audience_extend_list"
                  :key="item.value"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="projectFormCancel()">取消</el-button>
            <el-button
              type="primary"
              @click="projectFormSubmit('create')"
            >
              确认
            </el-button>
          </div>
        </template>
      </el-drawer>
      <el-drawer
        v-model="updateProjectDialog"
        size="60%"
        title="更新项目"
        width="800"
      >
        <el-form
          ref="project"
          :model="projectForm"
          label-position="top"
          :validate-on-rule-change="false"
        >
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>项目名称</span>
              </div>
            </template>
            <el-form-item
              label="项目名称"
              label-width="140px"
              prop="name"
            >
              <el-input
                v-model="projectForm.name"
                style="width: 50%;"
                @change="changeProjectName"
              />
            </el-form-item>
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>营销目的与场景</span>
              </div>
            </template>
            <el-form>
              <el-form-item
                label="推广目的"
              >
                小程序
              </el-form-item>
              <el-form-item
                label="广告类型"
              >
                通投广告
              </el-form-item>
              <el-form-item
                label="投放模式"
              >
                {{ projectForm.delivery_mode == 'MANUAL' ? '手动投放' : '自动投放' }}
              </el-form-item>
              <el-form-item
                label="营销场景"
              >
                {{ projectForm.marketing_goal == 'VIDEO_AND_IMAGE' ? '短视频+图片' : '直播' }}
              </el-form-item>
            </el-form>
          </el-card>
          <!-- <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>投放内容与目标</span>
              </div>
            </template>
            <el-form-item
              label="投放内容"
              label-width="140px"
              prop="micro_promotion_type"
            >
              <el-radio-group
                v-model="projectForm.micro_promotion_type"
              >
                <el-radio-button
                  v-for="(item,index) in micro_promotion_type_list"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="字节小游戏"
              label-width="140px"
              prop="micro_app_instance_id"
            >
              <el-select
                v-model="projectForm.micro_app_instance_id"
                style="width: 40%;"
                @change="changeMicroAppInstance"
              >
                <el-option
                  v-for="(item,index) in micro_app_instance_id_list"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="事件资产"
              label-width="140px"
              prop="asset_ids"
            >
              <el-select
                v-model.number="projectForm.optimize_goal.asset_ids[0]"
                style="width: 40%;"
              >
                <el-option
                  v-for="(item,index) in asset_ids_list"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="优化目标"
              label-width="140px"
              prop="external_action"
            >
              <el-select
                v-model="projectForm.optimize_goal.external_action"
                style="width: 30%;"
              >
                <el-option
                  v-for="(item,index) in external_action_list"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-card>
          <div v-if="marketCurValue.delivery_mode == 'MANUAL'">
            <el-divider />
            <el-card>
              <template #header>
                <div
                  class="card-header"
                >
                  <span>投放板位</span>
                </div>
              </template>
              <el-form-item
                label="投放位置"
                label-width="140px"
                prop="inventory_catalog"
              >
                <el-radio-group
                  v-model="projectForm.delivery_range.inventory_catalog"
                  style="width: 50%;"
                >
                  <el-radio-button
                    v-for="item in inventory_catalog_list"
                    :key="item.value"
                    :label="item.value"
                    :disabled="item.disabled"
                  >
                    {{ item.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-select
                v-if="projectForm.delivery_range.inventory_catalog == 'MANUAL'"
                v-model="projectForm.delivery_range.inventory_type"
                style="width: 40%;"
                multiple
                @chnage="changeInventoryType"
              >
                <el-option
                  v-for="(item,index) in inventory_type_list"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-card>
          </div> -->
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>用户定向</span>
              </div>
            </template>
            <audience-target
              :cur-value="curValue"
              :extensions="extensions"
              @receive="receive"
            />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div
                class="card-header"
              >
                <span>排期与预算</span>
              </div>
            </template>
            <budget-schedule
              :cur-value="budgetCurValue"
              :extensions="budgetExtensions"
              @receive="budgetReceive"
            />
          </el-card>
          <el-divider />
          <el-card v-if="searchControl">
            <template #header>
              <div
                class="card-header"
              >
                <span>搜索快投</span>
              </div>
            </template>
            <!-- <el-form-item
              label="关键词"
              label-width="140px"
            >
              <el-select
                v-model="keywordModel"
                multiple
                collapse-tags
                clearable
                filterable
                multiple-limit="1000"
                style="width: 25%;padding-right:10px"
              >
                <el-option
                  v-for="(item,index) in keywordList"
                  :key="index"
                  :label="item.word"
                  :value="item.word"
                />
              </el-select>
              <el-button
                type="primary"
                @click="openKeywordDialog"
              >添加/编辑</el-button>
            </el-form-item> -->
            <el-form-item
              label="出价系数"
              label-width="140px"
            >
              <el-input-number
                v-model="projectForm.search_bid_ratio"
                style="width: 20%;"
                :precision="2"
              />
            </el-form-item>
            <el-form-item
              label="定向扩展"
              label-width="140px"
            >
              <el-radio-group
                v-model="projectForm.audience_extend"
                style="width: 50%;"
              >
                <el-radio-button
                  v-for="item in audience_extend_list"
                  :key="item.value"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="updateProjectCancel()">取消</el-button>
            <el-button
              type="primary"
              @click="projectFormSubmit('update')"
            >
              更新
            </el-button>
          </div>
        </template>
      </el-drawer>
      <el-dialog
        v-model="keywordDialog"
        title="查询关键词"
      >
        <el-form>
          <el-form-item>
            <el-input
              v-model="keyword"
              placeholder="请输入关键词"
              style="width: 25%;padding-right: 10px;"
            />
            <el-button
              style="padding-right: 10px;"
              type="primary"
              @click="searchKeyword"
            >搜索
            </el-button>
            <el-button
              type="primary"
              @click="addKeywordAll"
            >全部添加:{{ keywordTotal }}个关键词</el-button>
          </el-form-item>
        </el-form>
        <div v-if="keywordTableData.length > 0">
          <el-scrollbar max-height="500px">
            <el-table
              :data="keywordTableData"
              style="width: 100%"
            >
              <el-table-column
                prop="keyword"
                label="关键词"
              />
              <el-table-column
                prop="msv"
                label="曝光量"
              />
              <el-table-column
                label="操作"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="addKeyword(scope.row)"
                  >添加</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>

      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAccountData,
  getHugeInfo,
} from '@/api/qmAccessTokens'
import { rpcGet } from '@/api/rpc'
import { getSuggestWords, createProject, updateProject, delProject, updateStatusProject } from '@/api/openApi'
import { useRouter, useRoute } from 'vue-router'

import JSONBIG from 'json-bigint'

import { setConfig } from '@bytedance-ad/mui-vue3'
import lodash from 'lodash'
import { jsonInBlacklist } from '@/api/jwt'

const router = useRouter()

const useRoutes = useRoute()

const account_id = Number(useRoutes.query.account_id)

// ======================================================

const keyword = ref()
const keywordDialog = ref(false)
const keywordList = ref([])
const keywordModel = ref([])
const keywordTotal = ref(0)
const keywordTableData = ref([])
const keywordAllTableData = ref([])

const openKeywordDialog = () => {
  keywordDialog.value = true
}

const searchKeyword = () => {
  if (keyword.value) {
    getSuggestWords({ advertiser_id: account_id, keyword: keyword.value }).then(res => {
      if (res.code == 0) {
        keywordTableData.value = []
        keywordAllTableData.value = res.data.list
        keywordTotal.value = res.data.list.length
        // 只取前100个
        res.data.list.slice(0, 100).forEach(item => {
          keywordTableData.value.push({
            keyword: item.keyword,
            msv: item.msv
          })
        })
      }
    })
  } else {
    ElMessage.error('请输入关键词')
  }
}

const addKeyword = (row) => {
  // 查询是否已经存在
  let flag = false
  keywordList.value.forEach(item => {
    if (item.word == row.keyword) {
      flag = true
    }
  })

  if (!flag) {
    keywordModel.value.push(row.keyword)
    keywordList.value.push({
      word: row.keyword,
    })
    ElMessage.success('添加成功')
  }
}

const addKeywordAll = () => {
  // 把关键词全部添加到关键词列表中 且不重复
  let num = 0
  keywordAllTableData.value.forEach(item => {
    let flag = false
    keywordList.value.forEach(model => {
      if (model.word == item.keyword) {
        flag = true
      }
    })
    if (!flag) {
      keywordModel.value.push(item.keyword)
      keywordList.value.push({
        word: item.keyword,
      })
      num++
    }
  })
  ElMessage.success('添加成功' + num + '个关键词')
}

setConfig({
  appId: '1806716056834058', // 必填，否则无法使用MUI, 可在后台管理系统https://open.oceanengine.com/developer/admin/ad_list获取
  host: import.meta.env.VITE_BASE_API,
  params: { // 可选，自定义每次请求的参数
    advertiser_id: account_id,
  },
  apis: {
    getDistrictList: '/openApi/tools/admin/info/',
    getCustomCrowdList: '/openApi/dmp/custom_audience/select/',
    getAwemeFanCategories: '/openApi/tools/aweme_multi_level_category/get/',
    getAwemeAuthorInfo: '/openApi/tools/aweme_author_info/get/',
    getAwemeSearchInfo: '/openApi/tools/aweme_info_search/',
    getAwemeFanAccounts: '/openApi/tools/aweme_category_top_author/get/',
    getAwemeSimilarAccounts: '/openApi/tools/aweme_similar_author_search/',
    getActionCategories: '/openApi/tools/interest_action/action/category/',
    getInterestCategories: '/openApi/tools/interest_action/interest/category/',
    getActionKeywords: '/openApi/tools/interest_action/action/keyword/',
    getInterestKeywords: '/openApi/tools/interest_action/interest/keyword/',
    getActionInterestKeywordSuggest: '/openApi/tools/interest_action/keyword/suggest/',
    getInterestActionInfoByIs: '/openApi/tools/interest_action/id2word/',
  }
})

const changeProjectName = (name) => {
  projectForm.value.name = name
}

const curValue = ref({})

const budgetCurValue = ref({})

const marketCurValue = ref({})

const extensions = ref({
  landing_type: 'MICRO_GAME',
  ad_type: 'ALL',
  securityJsCode: '5e8b57d198fde1619cf2cc9713a423bd',
  securityKey: '087645653d83533737fd9a32a170ec71',
  hiddenComponents: []
})

const budgetExtensions = ref({
  landing_type: 'MICRO_GAME',
  delivery_mode: undefined,
})

const receive = (val) => {
  curValue.value = val
}
const budgetReceive = (val) => {
  budgetCurValue.value = val
}

const marketReceive = (val) => {
  marketCurValue.value = val
  budgetExtensions.value.delivery_mode = val.delivery_mode
  if (val.delivery_mode === 'MANUAL') {
    extensions.value.hiddenComponents = []
    projectForm.value.delivery_range = {
      inventory_catalog: undefined,
      inventory_type: []
    }
    searchControl.value = true
  } else {
    extensions.value.hiddenComponents = ['action', 'aweme', 'device', 'network', 'mobile_brand', 'mobile_price', 'media', 'auto_extend_targets', 'hide_if_exists']
    projectForm.value.delivery_range = {
      inventory_catalog: 'UNIVERSAL_SMART'
    }
    projectForm.value.audience_extend = undefined
    searchControl.value = false
  }
}

const projectFormRules = ref({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  landing_type: [
    { required: true, message: '请选择推广目的', trigger: 'blur' }
  ],
  delivery_mode: [
    { required: true, message: '请选择投放模式', trigger: 'blur' }
  ],
  marketing_goal: [
    { required: true, message: '请选择营销场景', trigger: 'blur' }
  ],
  ad_type: [
    { required: true, message: '请选择广告类型', trigger: 'blur' }
  ],
  micro_promotion_type: [
    { required: true, message: '请选择投放内容', trigger: 'blur' }
  ],
  micro_app_instance_id: [
    { required: true, message: '请选择字节小游戏', trigger: 'blur' }
  ],
  // asset_ids: [
  //   { required: true, message: '请选择事件资产', trigger: 'blur' }
  // ],
  // external_action: [
  //   { required: true, message: '请选择优化目标', trigger: 'blur' }
  // ],
  // inventory_catalog: [
  //   { required: true, message: '请选择投放位置', trigger: 'blur' }
  // ]
})

const hugeSelectColumn = ref([])

const temHugeSelectColumn = ref([])

const selectHugeColumn = () => {
  temHugeSelectColumn.value = []
  // 把选中的列加入到表格列中
  if (hugeSelectColumn.value.length > 0) {
    hugeSelectColumn.value.forEach(item => {
      hugeColumns.value.forEach(column => {
        if (item === column.prop) {
          temHugeSelectColumn.value.push(column)
        }
      })
    })
  } else {
    temHugeSelectColumn.value = hugeColumns.value
  }
}
const landing_type_list = reactive([
  {
    value: 'MICRO_GAME',
    label: '小程序推广'
  },
])

const delivery_mode_list = reactive([
  {
    value: 'MANUAL',
    label: '手动投放',
    disabled: false
  },
  {
    value: 'PROCEDURAL',
    label: '自动投放',
    disabled: false
  },
])

const marketing_goal_list = reactive([
  {
    value: 'VIDEO_AND_IMAGE',
    label: ' 短视频+图片',
    disabled: false
  },
  {
    value: 'LIVE',
    label: '直播',
    disabled: false
  },
])

const ad_type_list = reactive([
  {
    value: 'ALL',
    label: '通投广告',
    disabled: false
  },
  {
    value: 'SEARCH',
    label: '搜索广告',
    disabled: false
  },
])

const delivery_type_list = reactive([
  {
    value: 'NORMAL',
    label: '常规投放',
    disabled: false
  },
  {
    value: 'DURATION',
    label: '极速智投',
    disabled: false
  },
])

const micro_promotion_type_list = reactive([
  {
    value: 'BYTE_GAME',
    label: '字节小游戏'
  },
])

const inventory_catalog_list = reactive([
  {
    value: 'UNIVERSAL_SMART',
    label: '通投智选',
    disabled: false
  },
  {
    value: 'MANUAL',
    label: '首选媒体',
    disabled: false
  },
])

const inventory_type_list = reactive([
  {
    value: 'INVENTORY_FEED',
    label: '今日头条'
  },
  {
    value: 'INVENTORY_VIDEO_FEED',
    label: '西瓜视频'
  },
  {
    value: 'INVENTORY_AWEME_FEED',
    label: '抖音短视频'
  },
  {
    value: 'INVENTORY_TOMATO_NOVEL',
    label: '番茄小说'
  },
  {
    value: 'INVENTORY_UNION_SLOT',
    label: '穿山甲'
  },
  {
    value: 'UNION_BOUTIQUE_GAME',
    label: 'ohayoo精品游戏'
  },
  {
    value: 'INVENTORY_SEARCH',
    label: '搜索广告'
  },
])

const audience_extend_list = reactive([
  {
    value: 'ON',
    label: '开启'
  },
  {
    value: 'OFF',
    label: '关闭'
  },
])

const searchControl = ref(false)

const projectForm = ref({
  name: undefined,
  advertiser_id: account_id,
  project_id: undefined,
  operation: 'DISABLE',
  // landing_type: 'MICRO_GAME',
  delivery_mode: undefined,
  marketing_goal: undefined,
  // ad_type: undefined,
  // delivery_type: 'NORMAL',
  micro_promotion_type: 'BYTE_GAME',
  micro_app_instance_id: undefined,
  optimize_goal: {
    asset_ids: [],
    external_action: undefined,
  },
  delivery_range: {
    inventory_catalog: undefined,
    inventory_type: []
  },
  search_bid_ratio: undefined,
  audience_extend: 'ON',
  keywords: undefined,
  delivery_setting: undefined,
  track_url_setting: {
    send_type: 'SERVER_SEND'
  },
  audience: undefined,
})

const micro_app_instance_id_list = ref([])

const getMicroAppList = () => {
  const params = {
    advertiserId: account_id,
    platformId: 1
  }
  getHugeInfo({ type: 'getGames', params: JSON.stringify(params) }).then(res => {
    if (res.code == 0) {
      micro_app_instance_id_list.value = []
      const arr = JSONBIG.parse(res.data.info)
      arr.forEach(item => {
        micro_app_instance_id_list.value.push({
          value: item.instance_id.toString(),
          label: item.name + '(' + item.instance_id + ')'
        })
      })
    }
  })
}

const asset_ids_list = ref([])

const getAssetIds = () => {
  const params = {
    advertiserId: account_id,
    platformId: 1
  }
  getHugeInfo({ type: 'getAssets', params: JSON.stringify(params) }).then(res => {
    if (res.code == 0) {
      asset_ids_list.value = []
      const arr = JSONBIG.parse(res.data.info)
      arr.forEach(item => {
        asset_ids_list.value.push({
          value: Number(item.asset_id.toString()),
          label: item.name + '(' + item.asset_id + ')'
        })
      })
    }
  })
}

const external_action_list = ref([])

const getExternalActionList = () => {
  const params = {
    advertiserId: account_id,
    platformId: 1,
    instanceId: projectForm.value.micro_app_instance_id
  }
  getHugeInfo({ type: 'getExternal', params: JSON.stringify(params) }).then(res => {
    if (res.code == 0) {
      external_action_list.value = []
      const arr = JSON.parse(res.data.info)
      arr.forEach(item => {
        external_action_list.value.push({
          value: item.external_action,
          label: item.external_action_name
        })
      })
    }
  })
}

const createDialog = ref(false)

const create = () => {
  createDialog.value = true
  projectForm.value = {
    name: undefined,
    advertiser_id: account_id,
    operation: 'DISABLE',
    // landing_type: 'MICRO_GAME',
    // delivery_mode: undefined,
    marketing_goal: undefined,
    // ad_type: undefined,
    // delivery_type: 'NORMAL',
    micro_promotion_type: 'BYTE_GAME',
    micro_app_instance_id: undefined,
    optimize_goal: {
      asset_ids: [],
      external_action: undefined,
    },
    delivery_range: {
      inventory_catalog: undefined,
      inventory_type: []
    },
    search_bid_ratio: undefined,
    audience_extend: 'ON',
    keywords: undefined,
    delivery_setting: undefined,
    track_url_setting: {
      send_type: 'SERVER_SEND'
    },
    audience: undefined,
  }
  marketCurValue.value = {
    'landing_type': 'APP',
    'delivery_mode': 'MANUAL',
    'marketing_goal': 'VIDEO_AND_IMAGE',
    'ad_type': 'ALL',
    'app_promotion_type': 'DOWNLOAD'
  }
  curValue.value = {
    'district': 'NONE',
    'invoke_source': 'MUI',
    'superior_popularity_type': 'NONE',
    'gender': 'NONE',
    'hide_if_converted': 'NO_EXCLUDE',
    'hide_if_exists': 'UNLIMITED'
  }
  budgetCurValue.value = {
    'schedule_type': 'SCHEDULE_FROM_NOW',
    'bid_type': 'CUSTOM',
    'pricing': 'PRICING_OCPM',
    'budget_mode': 'BUDGET_MODE_INFINITE'
  }
  getMicroAppList()
  getAssetIds()
}

const projectFormCancel = () => {
  createDialog.value = false
}

const updateProjectCancel = () => {
  updateProjectDialog.value = false
}

const project = ref(null)

const projectFormSubmit = (type) => {
  if (type === 'create') {
    const originKeyword = []
    keywordModel.value.forEach(item => {
      originKeyword.push({
        word: item,
        bid_type: 'FEED_TO_SEARCH',
        match_type: 'EXTENSIVE'
      })
    })

    projectForm.value.keywords = originKeyword
  }

  // 合并数据
  projectForm.value.delivery_setting = budgetCurValue.value

  projectForm.value.audience = curValue.value

  if (projectForm.value.search_bid_ratio == 0) {
    projectForm.value.search_bid_ratio = undefined
  }

  if (type === 'create') {
    const data = lodash.cloneDeep({
      ...projectForm.value,
      ...marketCurValue.value,
    })

    data.advertiser_id = Number(data.advertiser_id)
    const params = {
      ProjectCreateV30Request: JSON.stringify(data),
      micro_id: data.micro_app_instance_id,
      server: 'HugeServiceServer.createProject'
    }

    rpcGet(params).then(res => {
      if (res.code == 0) {
        if (res.data.code == 0) {
          ElMessage.success('添加项目成功')
          setTimeout(() => {
            location.reload()
          }, 1500)
        } else {
          ElMessage.error(res.data.message)
        }
      } else {
        ElMessage.error(res.message)
      }
    })
    // createProject(params).then(res => {
    //   if (res.code == 0) {
    //     ElMessage.success('添加项目成功')
    //     location.reload()
    //   }
    // })
  } else {
    const data = {
      name: projectForm.value.name,
      advertiser_id: Number(projectForm.value.advertiser_id),
      search_bid_ratio: projectForm.value.search_bid_ratio,
      audience_extend: projectForm.value.audience_extend,
      keywords: projectForm.value.keywords,
      audience: projectForm.value.audience,
      delivery_setting: projectForm.value.delivery_setting,
    }

    // 循环判断audience 和 delivery_setting 中是否存在null 存在就删除
    for (const key in data.audience) {
      if (data.audience[key] === null) {
        delete data.audience[key]
      }
    }

    for (const key in data.delivery_setting) {
      if (data.delivery_setting[key] === null) {
        delete data.delivery_setting[key]
      }
    }

    const params = {
      ProjectUpdateV30Request: JSON.stringify(data),
      project_id: projectForm.value.project_id,
      server: 'HugeServiceServer.updateProject'
    }
    rpcGet(params).then(res => {
      if (res.code == 0) {
        if (res.data.code == 0) {
          ElMessage.success('更新项目成功')
          setTimeout(() => {
            location.reload()
          }, 1500)
        } else {
          ElMessage.error(res.data.message)
        }
      } else {
        ElMessage.error(res.message)
      }
    })
  }
}

const updateProjectDialog = ref(false)

const editProject = (row) => {
  getMicroAppList()
  getAssetIds()
  const origin = originHugeTableData.value[row.project_id]
  projectForm.value.project_id = origin.project_id

  if (origin.delivery_mode === 'MANUAL') {
    extensions.value.hiddenComponents = []
    projectForm.value.delivery_range = {
      inventory_catalog: undefined,
      inventory_type: []
    }
    searchControl.value = true
  } else {
    extensions.value.hiddenComponents = ['action', 'aweme', 'device', 'network', 'mobile_brand', 'mobile_price', 'media', 'auto_extend_targets', 'hide_if_exists']
    projectForm.value.delivery_range = {
      inventory_catalog: 'UNIVERSAL_SMART'
    }
    projectForm.value.audience_extend = undefined
    searchControl.value = false
  }

  projectForm.value.marketing_goal = origin.marketing_goal
  projectForm.value.delivery_mode = origin.delivery_mode

  projectForm.value.name = origin.name
  projectForm.value.advertiser_id = account_id
  projectForm.value.micro_promotion_type = 'BYTE_GAME'
  projectForm.value.micro_app_instance_id = origin.micro_app_instance_id.toString()
  projectForm.value.optimize_goal = {
    asset_ids: origin.optimize_goal.asset_ids,
    external_action: origin.optimize_goal.external_action,
  }
  projectForm.value.delivery_range = origin.delivery_range
  projectForm.value.search_bid_ratio = origin.search_bid_ratio
  projectForm.value.audience_extend = origin.audience_extend
  projectForm.value.keywords = undefined
  // projectForm.value = {
  //   name: origin.name,
  //   operation: undefined,
  //   advertiser_id: account_id,
  //   micro_promotion_type: 'BYTE_GAME',
  //   micro_app_instance_id: origin.micro_app_instance_id.toString(),
  //   optimize_goal: {
  //     asset_ids: origin.optimize_goal.asset_ids,
  //     external_action: origin.optimize_goal.external_action,
  //   },
  //   delivery_range: origin.delivery_range,
  //   search_bid_ratio: origin.search_bid_ratio,
  //   audience_extend: origin.audience_extend,
  //   keywords: origin.keywords,
  //   delivery_setting: origin.delivery_setting,
  //   track_url_setting: origin.track_url_setting,
  //   audience: origin.audience,
  // }
  marketCurValue.value = origin
  curValue.value = origin.audience
  budgetCurValue.value = origin.delivery_setting

  updateProjectDialog.value = true
}

const deleteProject = (row) => {
  // 弹框
  ElMessageBox.confirm('确定要删除项目吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rpcGet({ project_id: row.project_id, advertiser_id: account_id, server: 'HugeServiceServer.delProject' }).then(res => {
      if (res.code == 0) {
        if (res.data.code == 0) {
          ElMessage.success('删除成功')
          setTimeout(() => {
            location.reload()
          }, 1500)
        } else {
          ElMessage.error(res.data.message)
        }
      } else {
        ElMessage.error(res.message)
      }
    })
  })
}

const changeDeliveryType = (val) => {
  projectForm.value.marketing_goal = undefined
  if (val === 'NORMAL') {
    marketing_goal_list.forEach(item => {
      item.disabled = false
    })
  } else if (val === 'DURATION') {
    marketing_goal_list.forEach(item => {
      if (item.value === 'LIVE') {
        item.disabled = true
      }
    })
  }
}

const changeMicroAppInstance = () => {
  getExternalActionList()
}

const changeInventoryType = () => {
  projectForm.value.delivery_range.inventory_type = []
}

const changeDeliveryMode = (val) => {
  budgetExtensions.value.delivery_mode = val
  if (projectForm.value.delivery_mode === 'PROCEDURAL') {
    inventory_catalog_list.forEach(item => {
      if (item.value === 'MANUAL') {
        item.disabled = true
      }
    })
    projectForm.value.delivery_range.inventory_catalog = undefined
    projectForm.value.search_bid_ratio = undefined
    projectForm.value.audience_extend = undefined
    projectForm.value.keywords = undefined
  } else {
    inventory_catalog_list.forEach(item => {
      if (item.value === 'MANUAL') {
        item.disabled = false
      }
    })
  }
}

const changeAdType = (val) => {
  extensions.value.ad_type = val
  if (projectForm.value.ad_type === 'ALL') {
    projectForm.value.delivery_type = 'NORMAL'
    delivery_mode_list.forEach(item => {
      if (item.value === 'PROCEDURAL') {
        item.disabled = false
      }
    })
  } else {
    delivery_mode_list.forEach(item => {
      if (item.value === 'PROCEDURAL') {
        item.disabled = true
      }
    })
  }
  projectForm.value.delivery_range = {
    inventory_catalog: undefined,
    inventory_type: []
  }
}

const updateStatusProjectSwitch = (row) => {
  const params = {
    advertiser_id: account_id,
    data: {
      project_id: row.project_id,
      opt_status: row.operationStatus ? 'ENABLE' : 'DISABLE'
    }

  }
  updateStatusProject(params).then(res => {
    if (res.code == 0) {
      ElMessage.success('操作成功')
    }
  })
}

const options = [
  {
    value: 'PROJECT_STATUS_NOT_DELETE',
    label: '不限'
  },
  {
    value: 'PROJECT_STATUS_DISABLE',
    label: '未投放',
    children: [
      {
        value: 'PROJECT_STATUS_STOP',
        label: '已暂停',
      },
      {
        value: 'PROJECT_STATUS_BUDGET_EXCEED',
        label: '项目超出预算',
      },
      {
        value: 'PROJECT_STATUS_NOT_START',
        label: '未达投放时间',
      },
      {
        value: 'PROJECT_STATUS_NO_SCHEDULE',
        label: '不在投放时段',
      },
    ],
  },
  {
    value: 'PROJECT_STATUS_ENABLE',
    label: '启用中'
  },
  {
    value: 'PROJECT_STATUS_DONE',
    label: '已完成'
  },
  {
    value: 'PROJECT_STATUS_DELETE',
    label: '已删除'
  },
  {
    value: 'PROJECT_STATUS_ALL',
    label: '不限(包含已删除)'
  }
]

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const hugeTableData = ref([])

const searchInfo = ref({
  advertiser_id: account_id,
  page: page.value,
  page_size: pageSize.value,
  keyword: '',
  status: undefined,
  platform_id: 1,
})

const handleCurrentChange = (val) => {
  page.value = val
  searchInfo.value.page = val
  getHugeTableData()
}

const temHugeTableData = ref([])

const originHugeTableData = ref({})

// 查询
const getHugeTableData = function() {
  getHugeInfo({ params: JSON.stringify(searchInfo.value), type: 'project' }).then(res => {
    if (res.code == 0) {
      hugeTableData.value = []
      temHugeTableData.value = []
      const info = JSONBIG.parse(res.data.info)
      total.value = info.PageInfo.total_number
      info.List.forEach(item => {
        const origin = JSONBIG.parse(item.origin)
        originHugeTableData.value[origin.project_id] = origin
        const extend = JSONBIG.parse(item.extend)
        const obj = {
          name: origin.name,
          project_id: origin.project_id,
          status: status.value[origin.status],
          status_first: status_first.value[origin.status_first],
          status_second: status_second.value[origin.status_second],
          budget: origin.delivery_setting.budget,
          time: origin.delivery_setting.start_time.split(' ')[0] + ' ~ ' + origin.delivery_setting.end_time.split(' ')[0],
          position: position.value[origin.delivery_range.inventory_catalog],
          cpa_bid: origin.delivery_setting.cpa_bid,
          operationStatus: false,
        }

        if (origin.status == 'PROJECT_STATUS_ENABLE') {
          obj.operationStatus = true
        }

        basicInfo.value.forEach(basic => {
          if (basic.label.indexOf('率') > -1) {
            obj[basic.prop] = extend[basic.prop] + '%'
          } else {
            obj[basic.prop] = extend[basic.prop]
          }
        })

        hugeTableData.value.push(obj)
      })
    }
  })
}

const position = ref({
  'MANUAL': '首选媒体',
  'UNIVERSAL_SMART': '通投智选',
})

const hugeColumns = ref([
  {
    label: '项目状态',
    prop: 'status',
    width: '150px'
  },
  {
    label: '一级状态',
    prop: 'status_first',
    width: '150px'
  },
  {
    label: '二级状态',
    prop: 'status_second',
    width: '150px'
  },
  {
    label: '项目预算',
    prop: 'budget',
    width: '100px'
  },

  {
    label: '投放时间',
    prop: 'time',
    width: '200px'
  },

  {
    label: '首选位置',
    prop: 'position',
    width: '100px'
  },
  {
    label: '项目出价',
    prop: 'cpa_bid',
    width: '100px'
  },
  {
    'label': '消耗',
    'prop': 'stat_cost',
    width: '100px'
  },
  {
    'label': '曝光',
    'prop': 'show_cnt'
  },
  {
    'label': '千次曝光',
    'prop': 'cpm_platform',
    width: '100px'
  },
  {
    'label': '点击率',
    'prop': 'ctr'
  },
  {
    'label': '转化数',
    'prop': 'attribution_convert_cnt'
  },
  {
    'label': '转化成本',
    'prop': 'attribution_convert_cost',
    width: '100px'
  },
  {
    'label': '转化率',
    'prop': 'attribution_conversion_rate'
  },
  {
    'label': '激活数',
    'prop': 'active'
  },
  {
    'label': '激活成本',
    'prop': 'active_cost',
    width: '100px'
  },
  {
    'label': '激活率',
    'prop': 'active_rate'
  },
  {
    'label': '次留',
    'prop': 'attribution_next_day_open_rate'
  },
  {
    'label': '二留',
    'prop': 'attribution_retention_2d_rate'
  },
  {
    'label': '三留',
    'prop': 'attribution_retention_3d_rate'
  },
  {
    'label': '七留',
    'prop': 'attribution_retention_7d_rate'
  },
  {
    'label': '行为数',
    'prop': 'game_addiction',
    width: '100px'
  },
  {
    'label': '行为成本',
    'prop': 'game_addiction_cost',
    width: '100px'
  },
  {
    'label': '行为达成率',
    'prop': 'game_addiction_rate',
    width: '100px'
  },
  {
    'label': '当日LTV',
    'prop': 'attribution_micro_game_0d_ltv',
    width: '150px'
  },
  {
    'label': '三日LTV',
    'prop': 'attribution_micro_game_3d_ltv',
    width: '150px'
  },
  {
    'label': '七日LTV',
    'prop': 'attribution_micro_game_7d_ltv',
    width: '150px'
  },

  {
    'label': '当日ROI',
    'prop': 'attribution_micro_game_0d_roi',
    width: '150px'
  },
  {
    'label': '三日ROI',
    'prop': 'attribution_micro_game_3d_roi',
    width: '150px'
  },
  {
    'label': '七日ROI',
    'prop': 'attribution_micro_game_7d_roi',
    width: '150px'
  },

])

const setColumn = () => {
  temHugeSelectColumn.value = []
  hugeColumns.value.forEach(item => {
    temHugeSelectColumn.value.push(item)
  })
}

setColumn()

const advertList = (row) => {
  router.push({
    name: 'qmAccountAdvert', query: { project_id: row.project_id, advertiser_id: account_id }
  })
}

const basicInfo = ref(
  [
    {
      'label': '消耗',
      'prop': 'stat_cost'
    },
    {
      'label': '曝光',
      'prop': 'show_cnt'
    },
    {
      'label': '千次曝光',
      'prop': 'cpm_platform'
    },
    {
      'label': '点击率',
      'prop': 'ctr'
    },
    {
      'label': '转化数',
      'prop': 'attribution_convert_cnt'
    },
    {
      'label': '转化成本',
      'prop': 'attribution_convert_cost'
    },
    {
      'label': '转化率',
      'prop': 'attribution_conversion_rate'
    },
    {
      'label': '激活数',
      'prop': 'active'
    },
    {
      'label': '激活成本',
      'prop': 'active_cost'
    },
    {
      'label': '激活率',
      'prop': 'active_rate'
    },
    {
      'label': '次留',
      'prop': 'attribution_next_day_open_rate'
    },
    {
      'label': '二留',
      'prop': 'attribution_retention_2d_rate'
    },
    {
      'label': '三留',
      'prop': 'attribution_retention_3d_rate'
    },
    {
      'label': '七留',
      'prop': 'attribution_retention_7d_rate'
    },
    {
      'label': '行为数',
      'prop': 'game_addiction'
    },
    {
      'label': '行为成本',
      'prop': 'game_addiction_cost'
    },
    {
      'label': '行为达成率',
      'prop': 'game_addiction_rate'
    },
    {
      'label': '当日LTV',
      'prop': 'attribution_micro_game_0d_ltv'
    },
    {
      'label': '三日LTV',
      'prop': 'attribution_micro_game_3d_ltv'
    },
    {
      'label': '七日LTV',
      'prop': 'attribution_micro_game_7d_ltv'
    },

    {
      'label': '当日ROI',
      'prop': 'attribution_micro_game_0d_roi'
    },
    {
      'label': '三日ROI',
      'prop': 'attribution_micro_game_3d_roi'
    },
    {
      'label': '七日ROI',
      'prop': 'attribution_micro_game_7d_roi'
    },

  ]
)

const status = ref(
  {
    'PROJECT_STATUS_ENABLE': '启用',
    'PROJECT_STATUS_DISABLE': '暂停',
    'PROJECT_STATUS_DELETE': '删除',
    'PROJECT_STATUS_BUDGET_EXCEED': '预算超出',
    'PROJECT_STATUS_BUDGET_PRE_OFFLINE_BUDGET': '项目接近预算',
    'PROJECT_STATUS_NOT_START': '未达投放时间',
    'PROJECT_STATUS_DONE': '已完成',
    'PROJECT_STATUS_NO_SCHEDULE': ' 不在投放时段'
  }
)
const status_first = ref({
  'PROJECT_STATUS_DELETE': '已删除',
  'PROJECT_STATUS_DONE': '已完成',
  'PROJECT_STATUS_DISABLE': '未投放',
  'PROJECT_STATUS_ENABLE': '启用中',
})

const status_second = ref({
  'PROJECT_STATUS_STOP': '已暂停',
  'PROJECT_STATUS_BUDGET_EXCEED': '预算超出',
  'PROJECT_STATUS_NOT_START': '未达投放时间',
  'PROJECT_STATUS_NO_SCHEDULE': '不在投放时段',
  'PROJECT_STATUS_BUDGET_GROUP_OFFLINE_BUDGET': '预算组超出预算',
})

const search = () => {
  getHugeTableData()
}

getHugeTableData()

</script>
<style scoped>
.el-col {
  text-align: center;
}

/*
/deep/ .el-form-item__label {
  font-weight: 700 !important;;
} */
</style>
